<?php

namespace hpnApp\nCtrl {

require_once(ABSPATH . '/MiiLib/Cmn.php');

use \hpnWse\stNumUtil;
use \hpnWse\stStrUtil;
use \hpnWse\stObjUtil;
use \hpnWse\stAryUtil;
use \hpnWse\stHttpSvc;
use \hpnWse\stSqlUtil;
use \hpnWse\nWp\stBase as stWpBase;

/// 控制器 - 索引
class stCtrl_index extends \hpnWse\stCtrl
{
	// public static function _miss($a_Mod, $a_Ctrl, $a_Actn)
	// {
	// 	// return stHttpSvc::cRspsErr(404, -1, 
	// 	// 	('模块控制器动作“' . $a_Mod . ' > ' . $a_Ctrl . ' > ' . $a_Actn . '”不存在！'));

	// 	return array('data' => 404);
	// }

	/// 默认，列出所有接口！
	public static function GET_default($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('列出全部控制器动作', null, array('data' => 'API列表'));
		}

		/// 列出全部控制器动作
		$l_RspsJson = array(
			'data' => stHttpSvc::cGetAllCtrlActn()
		);
		return $l_RspsJson;
	}

	public static function GET_cgr($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('响应联合GET请求', 
				array('json' => '列出要调用的接口参数，为每个请求起个名字作为键'), 
				array('data' => '对应各个GET请求的响应，键就是请求参数“json”里的键'));
		}

		return stHttpSvc::cRspsCgr(stObjUtil::cFchPpty($a_Prms, 'json'));
	}

	public static function GET_image_captcha($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('获取图像验证码');
		}

		require_once(\hpnWse\fGetWseDiry() . 'hpnWse/nSpu/nCaptcha/TextImg.php');
		$l_Rst = \hpnWse\nSpu\nCaptcha\stTextImg::cRun(null);
		$_SESSION['ImageCaptcha'] = $l_Rst['c_Code'];
	//	file_put_contents(__DIR__ . '/captcha.txt', print_r($l_Rst, true));
	}

	public static function GET_is_username_available($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('用户名是否可用？');
		}

		$l_Username = stObjUtil::cFchPpty($a_Prms, 'username');

		$l_Pdo = stHttpSvc::cCnctToDb();
		$l_Amt = stSqlUtil::cReadRowAmt_Cmpr($l_Pdo, (DB_NAME . '.t_user'), 'mUsername', '=', $l_Username);		
		return array('data' => (0 == $l_Amt));
	}

	public static function GET_is_email_available($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('邮箱是否可用？');
		}

		$l_Email = stObjUtil::cFchPpty($a_Prms, 'email');

		$l_Pdo = stHttpSvc::cCnctToDb();
		$l_Amt = stSqlUtil::cReadRowAmt_Cmpr($l_Pdo, (DB_NAME . '.t_user'), 'mEmail', '=', $l_Email);		
		return array('data' => (0 == $l_Amt));
	}

	public static function POST_signup($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('注册');
		}

		if (!isset($_SESSION['ImageCaptcha']))
		{
			return stHttpSvc::cRspsErr(400, -2, '请刷新验证码，然后提交！');
		}

		$l_SD = $a_Prms['json'];

		$l_V_Email = \hpnWse\nMvc\nVldtr\fEmail(true);
		$l_V_Spw = \hpnWse\nMvc\nVldtr\fSpw(true);

		$l_V_Password = '{
			"c_Tpnm": "tStrLenRge",
			"c_Info": "密码长度 8 - 20 个字符",
			"c_Min": 8,
			"c_Max": 20
		}';
		
		$l_CaptchaCode = $_SESSION['ImageCaptcha'];
		$l_V_Captcha = new \hpnWse\nMvc\nVldtr\tEq($l_CaptchaCode, '验证码错误');
		$l_V_Captcha = \hpnWse\nMvc\stFvMgr::cToJsonStr($l_V_Captcha);

$l_MdlJson = <<<JSON
{
	"username": {
		"Wse_Val": "",
		"Wse_Optns": {
			"c_Rqrd": 1
		},
		"Wse_Vldtrs": [
			{
				"c_Tpnm": "tStrLenRge",
				"c_Min": 2,
				"c_Max": 20
			}
		]
	}
	,
	"email": {
		"Wse_Val": "",
		"Wse_Optns": {
			"c_Rqrd": 1
		},
		"Wse_Vldtrs": [
			$l_V_Email
		]
	}
	,
	"password": {
		"Wse_Val": "",
		"Wse_Optns": {
			"c_Rqrd": 1
		},
		"Wse_Vldtrs": [
			$l_V_Password
		]
	}
	,
	"password2": {
		"Wse_Val": "",
		"Wse_Optns": {
			"c_Rqrd": 1
		},
		"Wse_Vldtrs": [
			$l_V_Spw
		]
	}
	,
	"captcha": {
		"Wse_Val": "",
		"Wse_Optns": {
			"c_Rqrd": 1
		},
		"Wse_Vldtrs": [
			$l_V_Captcha
		]
	}
}
JSON;

	//	unset($_SESSION['ImageCaptcha']); // 无论成败，都要清除验证码【留着吧，以便改正】

		$l_MdlJson = stObjUtil::cDcdJson($l_MdlJson);
		$l_VM = new \hpnWse\nMvc\tMdl($l_MdlJson, true);
		$l_VM->cAllFldsAcpErr(true);
		$l_VM->cUpdFldsFromJson($l_SD);

		$l_ErrInfo = array();
		$l_VR = $l_VM->cVldt($l_ErrInfo);
		if (!$l_VR)
		{
			return stHttpSvc::cRspsErr(400, -2, '提交的数据存在错误！', $l_ErrInfo);
		}

		$l_SignupTmstp = time();
		$l_SignupDatm = date("Y-m-d H:i:s", $l_SignupTmstp);

		// 存入WP
		$l_UserData = array(
			'user_login' => $l_VM->cReadFld('username'),
			'user_pass' => $l_VM->cReadFld('password'),
			'user_email' => $l_VM->cReadFld('email'),
		);
		$l_Aid = wp_insert_user($l_UserData);
		if (!$l_Aid)
		{
			return stHttpSvc::cRspsErr(500, -2, '录入数据库时发生未知错误！');
		}

		// 存入数据库
		$l_Pdo = stHttpSvc::cCnctToDb();
		$l_Db = DB_NAME;

$l_Sql = <<<SQL
INSERT INTO $l_Db.t_user
(mId, mUsername, mEmail, mPassHash, mSignupDatm, mActionLock)
VALUES
($l_Aid, :mUsername, :mEmail, :mPassHash, :mSignupDatm, :mActionLock)
SQL;
		try
		{
			$l_Afcd = stSqlUtil::cPrprExec($l_Pdo, $l_Sql, 
				array(
					'mUsername' => $l_VM->cReadFld('username'),
					'mEmail' => $l_VM->cReadFld('email'),
					'mPassHash' => md5(\hpnWse\stHttpSvc::$c_PdoCfg['c_Salt'] . $l_VM->cReadFld('password')),
					'mSignupDatm' => $l_SignupDatm,
					'mActionLock' => $l_SignupDatm,
				));
		}
		catch (\Exception $a_Exc)
		{
			return stHttpSvc::cRspsErr(500, -2, '用户名或邮箱已被注册', $a_Exc->getMessage());
		}
		if (1 !== $l_Afcd)
		{
			return stHttpSvc::cRspsErr(500, -2, '录入数据库时发生未知错误！');
		}

	//	$l_AutoId = strval($l_Pdo->lastInsertId());
		$l_AutoId = $l_Aid;

	// 	// 发送邮件
	// //	self::eSendEmail_signup($l_VM->cReadFld('phone'), $l_VM->cReadFld('concern'));
	// 	require_once(\hpnWse\fGetWseDiry() . 'hpnWse/nSpu/nEmail/Send.php');
	// 	$l_RunRst = \hpnWse\nSpu\nEmail\stSend::cRun(array(
	// 		'c_Usnm' => '18753295539@163.com',
	// 		'c_Pswd' => 'liyongheng1',
	// 		'c_FromName' => '师承手机站2',
	// 		'c_To' => \hpnWse\fIsDvlpMode() ? '826058677@qq.com' : '2573144969@qq.com',
	// 		'c_Sbjc' => '新用户注册',
	// 		'c_Body' => $l_VM->cReadFld('phone')
	// 	));

		// 重建会话，记录登录信息
		session_regenerate_id();
		$_SESSION['UserProfile'] = array(
			'Id' => $l_AutoId,
			'Username' => $l_VM->cReadFld('username'),
			'Email' => $l_VM->cReadFld('email'),
			'SignupDatm' => $l_SignupDatm
		);
		return array('data'=> $_SESSION['UserProfile']);
	}

	public static function POST_login($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('登录');
		}

		//【允许重复登录】
		// if (stObjUtil::cFchPpty($_SESSION, 'UserProfile'))
		// {
		// 	return stHttpSvc::cRspsErr(400, -2, '已登录');
		// }

		if (!isset($_SESSION['ImageCaptcha']))
		{
			return stHttpSvc::cRspsErr(400, -2, '请刷新验证码，然后提交！');
		}

		//【立即删除验证码】
		$l_CaptchaCode = $_SESSION['ImageCaptcha'];
		unset($_SESSION['ImageCaptcha']);

		//【检查令牌】
		$l_SD = $a_Prms['json'];
		// $l_PostToken = trim(stObjUtil::cFchPpty($l_SD, 'post_token'));
		// if (!isset($_SESSION['PostToken']) || ($l_PostToken !== $_SESSION['PostToken']))
		// {
		// 	// \hpnWse\stObjUtil::cDcdJson($_POST['json'])
		// 	return stHttpSvc::cRspsErr(400, -2, '请刷新后重试！');// . print_r(\hpnWse\stObjUtil::cDcdJson($_POST['json']), true));
		// }

		if (\hpnWse\stObjUtil::cFchPpty($l_SD, 'captcha') !== $l_CaptchaCode)
		{
			return stHttpSvc::cRspsErr(400, -2, '验证码错误，请刷新验证码！');
		}

		$l_UE = trim(stObjUtil::cFchPpty($l_SD, 'username'));
		$l_Password = trim(stObjUtil::cFchPpty($l_SD, 'password'));
		if (!$l_UE) { return stHttpSvc::cRspsErr(400, -2, '必须提供用户名或邮箱'); }
		if (!$l_Password) { return stHttpSvc::cRspsErr(400, -2, '必须提供密码'); }

		$l_PassHash = md5(\hpnWse\stHttpSvc::$c_PdoCfg['c_Salt'] . $l_Password);
		$l_Pdo = stHttpSvc::cCnctToDb();
		$l_Db = DB_NAME;
		$l_One = null;

		if (\hpnWse\stStrUtil::cFind($l_UE, '@') < 0)
		{
$l_Sql = <<<SQL
SELECT mId, mUsername, mEmail, mSignupDatm
FROM $l_Db.t_user
WHERE mUsername = :mUsername AND mPassHash = :mPassHash
SQL;
		$l_One = stSqlUtil::cPrprExecFchOne($l_Pdo, $l_Sql,
			array(
				'mUsername' => $l_UE,
				'mPassHash' => $l_PassHash
			));
		}
		else
		{
$l_Sql = <<<SQL
SELECT mId, mUsername, mEmail, mSignupDatm
FROM $l_Db.t_user
WHERE mEmail = :mEmail AND mPassHash = :mPassHash
SQL;
		$l_One = stSqlUtil::cPrprExecFchOne($l_Pdo, $l_Sql,
			array(
				'mEmail' => $l_UE,
				'mPassHash' => $l_PassHash
			));
		}

		if (!$l_One)
		{
			return stHttpSvc::cRspsErr(400, -2, '用户名或邮箱或密码错误！');
		}

		// 重建会话，记录登录信息
		session_regenerate_id();
		$_SESSION['UserProfile'] = array(
			'Id' => strval($l_One['mId']),
			'Username' => $l_One['mUsername'],
			'Email' => $l_One['mEmail'],
			'SignupDatm' => $l_One['mSignupDatm']
		);
		return array('data'=> $_SESSION['UserProfile']);
	}

	public static function POST_logout($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('登出');
		}

		// 重建会话，记录登录信息
		session_destroy();
		$_SESSION = array();
		return array('data' => null);
	}

	private static function eSendEmail_signup($a_Phone, $a_Concern)
	{
	//	$a_Phone = htmlspecialchars($a_Phone);
		switch ($a_Concern) 
		{
			case 0: { $l_Concern = '留学'; } break;
			case 1: { $l_Concern = '考研'; } break;
			case 2: { $l_Concern = '医学'; } break;
			case 3: { $l_Concern = '中医'; } break;
		}

$l_Sbjc = '官网新注册用户';
$l_Html = <<<HTML
<div>电话：$a_Phone</div>
<div>关注：$l_Concern</div>
HTML;
		return self::eSendEmail_($l_Sbjc, $l_Html);
	}

	private static function eSendEmail_($a_Sbjc, $a_Html)
	{
		require_once(\hpnWse\fGetWseDiry() . 'hpnWse/nSpu/nEmail/Send.php');
		$l_RunRst = \hpnWse\nSpu\nEmail\stSend::cRun(array(
			'c_Usnm' => '18753295539@163.com',
			'c_Pswd' => 'liyongheng1',
			'c_FromName' => '中域官网',
			'c_To' => \hpnWse\fIsDvlpMode() ? '826058677@qq.com' : 'wangjc@zhongyuedu.com',
			'c_Sbjc' => $a_Sbjc,
			'c_Body' => $a_Html
		));
		return $l_RunRst['c_IsSucs'];
	}
}

} // namespace \hpnApp\nCtrl

//////////////////////////////////// OVER ////////////////////////////////////